package com.soboot.system.controller;

import cn.hutool.core.util.StrUtil;
import com.soboot.base.model.BaseController;
import com.soboot.response.Result;
import com.soboot.system.service.IUserService;
import com.soboot.system.vo.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author:
 * @createTime: 2022年09月21日 10:31:15
 * @version: 1.0
 * @Description: 登录控制器
 * @Copyright:
 */
@RestController
public class LoginController extends BaseController {

    @Autowired
    private IUserService userService;

    @Autowired
    private TokenStore tokenStore;

    @GetMapping("/login/username/{username}")
    public Result<UserInfoVO> loginByUsername(@PathVariable String username) {

        UserInfoVO userInfo = userService.queryUser(username);
        return Result.success(userInfo);
    }

    @DeleteMapping("/logout/{token}")
    public Result logout(@PathVariable("token") String token) {
        if (StrUtil.isBlank(token)) {
            return Result.fail("退出失败，Token为空");
        }
        OAuth2AccessToken accessToken = tokenStore.readAccessToken(token);
        if (accessToken == null || StrUtil.isBlank(accessToken.getValue())) {
            return Result.success();
        }
        tokenStore.removeAccessToken(accessToken);
        OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
        tokenStore.removeRefreshToken(refreshToken);
        return Result.success();
    }
}
